package com.csii.ssm.aspect;

import com.csii.ssm.common.Dict;
import com.csii.ssm.exception.AccessRuntimeException;
import com.csii.ssm.exception.AccessRuntimeExceptionDict;
import com.csii.ssm.model.User;
import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by Charis on 2016/8/31.
 */
@Component("loginVerifyAspect")
@Scope("singleton")
public class LoginVerifyAspect {

    private static final Logger logger = LoggerFactory.getLogger(LoginVerifyAspect.class);
    private static final String PATHWITHINHANDLERMAPPING = "org.springframework.web.servlet.HandlerMapping.pathWithinHandlerMapping";


    /**
     * 切面前置  一定执行  验证用户的Session状态
     *
     * @param joinPoint
     * @throws Throwable
     */
    public void before(JoinPoint joinPoint) throws Throwable {
            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = attr.getRequest();
            HttpSession session = attr.getRequest().getSession();
            String transcodepath = (String) request.getAttribute(PATHWITHINHANDLERMAPPING);
            String transcode = transcodepath.substring(1, transcodepath.length());
            logger.debug("loginVerifyAspect @Before：===" + transcode + "=== 交易");
            User user = (User) session.getAttribute(Dict.LOGINUSER);
            if (user == null) {
                throw new AccessRuntimeException(AccessRuntimeExceptionDict.ERROR_USER_SESSION_INVALID);
            }
    }

}
